import pyautogui
import time
import os
import win32print
import win32api
import datetime
import threading

import requests

from app.config import Config
from app.tool.scriptWX.autoOperate import input_text, scroll_down, click_button

# 打开应用程序图标的函数
def open_application_by_icon(icon_image, max_attempts=3, timeout=5):
    attempts = 0
    while attempts < max_attempts:
        try:
            icon_location = pyautogui.locateCenterOnScreen(icon_image, confidence=0.8)
            if icon_location is not None:
                pyautogui.moveTo(icon_location)
                pyautogui.doubleClick()
                print(f"找到图标并点击，位置: {icon_location}")
                return True
            else:
                print(f"未找到图标: {icon_image}，正在重试... (第 {attempts + 1} 次)")
                attempts += 1
                time.sleep(timeout)

        except Exception as e:
            print(f"发生错误: {e}, 在尝试第 {attempts + 1} 次时")
            attempts += 1
            time.sleep(timeout)

    print(f"多次尝试后未找到图标: {icon_image}")
    return False


# 打印文件的函数
def control_printer(file_path):
    try:
        if not os.path.exists(file_path):
            print(f"文件未找到: {file_path}")
            return
        printer_name = win32print.GetDefaultPrinter()
        print(f"使用打印机: {printer_name}")
        win32api.ShellExecute(0, "print", file_path, None, ".", 0)
        print(f"文件 {file_path} 已发送到打印机 {printer_name}。")
    except Exception as e:
        print(f"打印时发生错误: {e}")


# 定时执行程序，增加可变参数支持，防止重复启动提醒
def check_time_and_remind(reminder_func, target_time, *reminder_args):
    print("定时提醒已启动...")
    reminder_triggered = False
    while True:
        current_time = datetime.datetime.now().strftime('%H:%M')

        if current_time == target_time and not reminder_triggered:
            threading.Thread(target=reminder_func, args=reminder_args).start()
            reminder_triggered = True
            time.sleep(60)

        if current_time != target_time:
            reminder_triggered = False

        time.sleep(1)


# 执行点击和写入的操作流程，并行执行任务
def execute_opt(opt_list, base_path):
    threads = []

    for opt in opt_list:
        thread = threading.Thread(target=perform_action, args=(opt, base_path))
        thread.start()
        threads.append(thread)

    # 等待所有线程任务完成
    for thread in threads:
        thread.join()

# 动作执行的函数
def perform_action(opt, base_path):
    action = opt.get("action")
    target = opt.get("target")
    address = target.get("address")
    path = os.path.join(base_path, address + ".png")

    # 点击操作
    if action == "click_double":
        if open_application_by_icon(path):
            time.sleep(2)
    elif action == "click":
        if click_button(path):
            time.sleep(2)
    # 输入操作
    elif action == "write":
        msg = target.get("content", "")
        print(f"输入内容: {msg}")
        input_text(msg)

    # 确认操作（滚动查找）
    elif action == "confirm":
        confirm_action(path)

    # 清除操作
    elif action == "quit":
        clear_application(opt, base_path)

# 单独处理确认操作，包含滚动查找
def confirm_action(path):
    max_scroll_attempts = 10
    attempts = 0
    while not open_application_by_icon(path) and attempts < max_scroll_attempts:
        scroll_down()
        attempts += 1
        time.sleep(1)
    open_application_by_icon(path)

# 单独处理清除操作
def clear_application(opt_list, base_path):
    last_opt = opt_list[-1]
    path = os.path.join(base_path, last_opt["target"]["address"] + ".png")
    open_application_by_icon(path)


# 使用大模型对文本进行总结并匹配操作数据
def understand_content(text, opeartes):
    API_ENDPOINT = Config.XIAOZHI_URL
    prompt = (f"以下是我的操作数据集合：{opeartes}。"
              f"我的问题是：'{text}'。"
              f"请从操作数据中匹配出符合我问题的那条数据，并**仅返回数据本身**，**不要附加任何解释或说明**。")

    payload = {
        "model": "llama3",
        "messages": [{"role": "user", "content": prompt}]
    }

    try:
        response = requests.post(API_ENDPOINT, json=payload)
        response.raise_for_status()
        summary = response.json()
        if summary['choices'][0]['message']['content']:
            return summary['choices'][0]['message']['content']
        return None
    except requests.exceptions.RequestException as e:
        print(f"Error summarizing text with large model: {e}")
        return None
